﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Text;

namespace LiveWriterBackupWPF
{
    public static class WLBDebug
    {
        public static void WriteToFile(string message)
        {
            StreamWriter debugLogWriter;
            long maxfilesize = 1048576;
            string debugFilePath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + "\\Windows Live Writer Backup";
            string debugFile = string.Format("{0}\\WLBackup.log", debugFilePath);

            if (File.Exists(debugFile))
            {
                FileInfo file = new FileInfo(debugFile);
                
                try
                {
                    if (file.Length > maxfilesize)
                    {
                        file.Delete();
                        WriteToFile(message);
                        return;
                    }
                    debugLogWriter = new StreamWriter(new FileStream(debugFile, FileMode.Append, FileAccess.Write, FileShare.None));
                }
                catch
                {
                    throw new ApplicationException("File locked");
                }
            }
            else
            {
                if (!Directory.Exists(debugFilePath))
                {
                    Directory.CreateDirectory(debugFilePath);
                }
                try
                {
                    debugLogWriter = new StreamWriter(new FileStream(debugFile, FileMode.CreateNew, FileAccess.Write, FileShare.None));
                }
                catch
                {
                    throw new ApplicationException("File locked");
                }
            }
            debugLogWriter.WriteLine(DateTime.Now.ToString() + ": " + message);
            debugLogWriter.Flush();
            debugLogWriter.Close();
        }
    }
}
